<template>
  <div class="admin-comments">
    <div class="container">
      <h1 class="page-title">评论管理</h1>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <template v-else>
        <!-- 搜索和筛选区域 -->
        <div class="filter-container">
          <el-input
            v-model="searchQuery"
            placeholder="搜索评论内容或用户名"
            class="search-input"
            clearable
            @clear="fetchComments"
          >
            <template #append>
              <el-button @click="fetchComments">
                <i class="el-icon-search"></i>
              </el-button>
            </template>
          </el-input>
          
          <div class="filter-actions">
            <el-button type="primary" @click="fetchComments">刷新</el-button>
          </div>
        </div>
        
        <!-- 评论列表 -->
        <el-card shadow="hover" class="comments-card">
          <div class="comments-list">
            <div v-if="commentsList.length === 0" class="no-data">
              <el-empty description="暂无评论数据" />
            </div>
            <div v-else>
              <el-table :data="commentsList" style="width: 100%" border>
                <el-table-column prop="id" label="ID" width="80" />
                <el-table-column prop="username" label="用户名" width="120" />
                <el-table-column prop="pet_name" label="宠物名称" width="120" />
                <el-table-column prop="comment" label="评论内容">
                  <template #default="scope">
                    <div class="comment-content-cell">{{ scope.row.comment }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="rating" label="评分" width="100">
                  <template #default="scope">
                    <el-rate
                      v-model="scope.row.rating"
                      disabled
                      show-score
                      text-color="#ff9900"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="created_at" label="创建时间" width="180">
                  <template #default="scope">
                    {{ formatDate(scope.row.created_at) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="scope">
                    <el-button 
                      type="danger" 
                      link 
                      @click="confirmDeleteComment(scope.row)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <!-- 分页 -->
              <div class="pagination-container">
                <el-pagination
                  background
                  layout="prev, pager, next, jumper"
                  :total="total"
                  :page-size="pageSize"
                  :current-page="currentPage"
                  @current-change="handlePageChange"
                />
              </div>
            </div>
          </div>
        </el-card>
      </template>
    </div>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
    >
      <span>确定要删除这条评论吗？此操作不可恢复。</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteComment" :loading="processing">
            确认删除
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义API_URL
const API_URL = process.env.VUE_APP_API_URL || 'http://localhost:3000/api';

export default {
  name: 'AdminComments',
  setup() {
    const router = useRouter()
    const route = useRoute()
    
    // 状态变量
    const loading = ref(true)
    const processing = ref(false)
    const commentsList = ref([])
    const searchQuery = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const deleteDialogVisible = ref(false)
    const commentToDelete = ref(null)
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '未知'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    // 获取评论列表
    const fetchComments = async () => {
      try {
        loading.value = true
        
        // 检查令牌是否存在
        const token = sessionStorage.getItem('token')
        if (!token) {
          ElMessage.error('未找到认证令牌，请重新登录后再试')
          router.push('/login')
          return
        }
        
        // 构建查询参数
        const params = {
          page: currentPage.value,
          limit: pageSize.value
        }
        
        if (searchQuery.value) {
          params.search = searchQuery.value
        }

        console.log('发送请求参数:', params)
        console.log('请求URL:', `${API_URL}/petcomments/recent`)
        console.log('请求头:', {
          'Authorization': `Bearer ${token}`,
          'x-auth-token': token
        })
        
        // 发送请求获取评论列表
        const response = await axios.get(`${API_URL}/petcomments/recent`, {
          params,
          headers: {
            'Authorization': `Bearer ${token}`,
            'x-auth-token': token
          }
        })
        
        console.log('API响应数据:', response.data)
        
        if (response.data && Array.isArray(response.data)) {
          console.log('设置评论列表:', response.data)
          commentsList.value = response.data
          total.value = response.data.length
        } else {
          console.log('响应数据格式不正确:', response.data)
          commentsList.value = []
          total.value = 0
        }
      } catch (error) {
        console.error('获取评论列表失败:', error)
        console.error('错误详情:', error.response ? error.response.data : '无响应数据')
        console.error('错误状态:', error.response ? error.response.status : '无状态码')
        ElMessage.error('获取评论列表失败，请稍后重试')
        commentsList.value = []
        total.value = 0
      } finally {
        loading.value = false
      }
    }
    
    // 处理页面变化
    const handlePageChange = (page) => {
      currentPage.value = page
      fetchComments()
    }
    
    // 确认删除评论
    const confirmDeleteComment = (comment) => {
      commentToDelete.value = comment
      deleteDialogVisible.value = true
    }
    
    // 删除评论
    const deleteComment = async () => {
      if (!commentToDelete.value) return
      
      try {
        processing.value = true
        
        // 检查令牌是否存在
        const token = sessionStorage.getItem('token')
        if (!token) {
          ElMessage.error('未找到认证令牌，请重新登录后再试')
          router.push('/login')
          return
        }
        
        // 发送删除请求
        await axios.delete(`${API_URL}/petcomments/${commentToDelete.value.id}`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'x-auth-token': token
          }
        })
        
        ElMessage.success('评论删除成功')
        deleteDialogVisible.value = false
        fetchComments() // 重新加载评论列表
      } catch (error) {
        console.error('删除评论失败:', error)
        ElMessage.error('删除评论失败，请稍后重试')
      } finally {
        processing.value = false
      }
    }
    
    // 监听搜索词变化，重置页码
    watch(searchQuery, () => {
      currentPage.value = 1
    })
    
    // 组件挂载时加载数据
    onMounted(() => {
      // 从URL参数中获取页码
      if (route.query.page) {
        currentPage.value = parseInt(route.query.page) || 1
      }
      
      // 加载评论列表
      fetchComments()
    })
    
    return {
      loading,
      processing,
      commentsList,
      searchQuery,
      currentPage,
      pageSize,
      total,
      deleteDialogVisible,
      formatDate,
      fetchComments,
      handlePageChange,
      confirmDeleteComment,
      deleteComment
    }
  }
}
</script>

<style scoped>
.admin-comments {
  padding: 20px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
}

.loading-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.filter-actions {
  display: flex;
  gap: 10px;
}

.comments-card {
  margin-bottom: 20px;
}

.comment-content-cell {
  max-width: 400px;
  white-space: normal;
  word-break: break-word;
  line-height: 1.5;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.no-data {
  padding: 40px 0;
  text-align: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>